﻿using CY_MVC.Utility;
using Fasterflect;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Linq;

namespace CY_MVC.Core
{
    internal static class AjaxMethodContext
    {
        internal static void Init()
        {
            foreach (var ItemA in ControllerContext.Controllers)
            {
                foreach (var Methodinfo in ItemA.Value.GetMethods())
                {
                    var Key = AjaxMethod.TypeMethodName(ItemA.Value, Methodinfo);
                    var Parameterinfos = Methodinfo.GetParameters().ToDictionary(parameterInfo => parameterInfo.Name.ToLowerInvariant());
                    var Paramtypes = new List<Type>();
                    foreach (var parameter in Parameterinfos)
                    {
                        Paramtypes.Add(parameter.Value.ParameterType);
                    }
                    var MethodInvoker = ItemA.Value.DelegateForCallMethod(Methodinfo.Name, Paramtypes.ToArray());
                    try
                    {
                        AjaxMethod.AjaxMethodList.Add(Key, MethodInvoker);
                        AjaxMethod.AjaxParameterInfoList.Add(Key, Parameterinfos);
                    }
                    catch
                    {
                        throw new Exception(Key + "重复");
                    }
                }
            }
        }

        internal static string Invoke(object p_Targetobject, string p_Methodname, NameValueCollection p_Param)
        {
            return AjaxMethod.Invoke(p_Targetobject, p_Methodname, p_Param.AllKeys.ToDictionary(Key => Key.Trim().ToLowerInvariant(), Key => p_Param[Key]));
        }
    }
}